package io.wjc.config;

import io.wjc.common.BytesSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * springboot默认使用LettuceConnectionFactory连接工程，经过测试发现使用LettuceConnectionFactory 连接工厂，获取一次连接，比JedisConnectionFactory要慢20倍
 * @author: wangjc
 * 2020/4/18
 */
@Configuration
public class RedisConfig {
//    这种直接new 出来的 JedisConnectionFactory，无法获取到application.yml中的配置，必须通过JedisConnectionConfiguration初始化JedisConnectionFactory才能获取到配置
//    @Bean
//    public JedisConnectionFactory redisConnectionFactory() {
//        return new JedisConnectionFactory().;
//    }


    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();

        BytesSerializer bytesSerializer = new BytesSerializer();
        redisTemplate.setKeySerializer(bytesSerializer);
        redisTemplate.setValueSerializer(bytesSerializer);

        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }


//    @Bean
//    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
//        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
//        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
//        JdkSerializationRedisSerializer fastJsonRedisSerializer = new JdkSerializationRedisSerializer();
//
//        redisTemplate.setKeySerializer(stringSerializer);
//        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
//
//        redisTemplate.setHashKeySerializer(stringSerializer);
//        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
//
//        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
//        redisTemplate.afterPropertiesSet();
//        return redisTemplate;
//    }
}
